<script lang="ts" setup>
import { ref, watch } from 'vue';

const props = withDefaults(
  defineProps<{
    startPlaceholder?: string;
    endPlaceholder?: string;
    disableBeforeToday?: boolean;
  }>(),
  {
    startPlaceholder: '请选择开始时间',
    endPlaceholder: '请选择结束时间',
    disableBeforeToday: true,
  },
);

const startDate = ref<Date | undefined>(undefined);
const endDate = ref<Date | undefined>(undefined);
const endDateDisable = ref<boolean>(true);

const emits = defineEmits(['changeStartTime', 'onChange']);

const startDisabledDate = (time: Date) => {
  if (props.disableBeforeToday) return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};

const endDisabledDate = (time: Date) => {
  if (startDate.value) return time.getTime() < startDate.value.getTime() + 1000 * 60 * 60 * 24;
};

watch(
  () => startDate.value,
  (val) => {
    if (!val) {
      endDateDisable.value = true;
      endDate.value = undefined;
      return;
    }
    endDateDisable.value = false;
    emits('changeStartTime', val);
  },
);

watch(
  () => endDate.value,
  (val) => {
    val &&
      emits('onChange', {
        startDate: startDate.value,
        endDate: val,
      });
  },
);
</script>

<template>
  <div>
    <div class="choose-date">
      <div class="start-date">
        <el-date-picker
          v-model="startDate"
          type="date"
          :placeholder="startPlaceholder"
          :disabled-date="startDisabledDate"
          v-bind="$attrs.startOptions"
        >
        </el-date-picker>
      </div>
      <div class="end-date">
        <el-date-picker
          v-model="endDate"
          type="date"
          :placeholder="endPlaceholder"
          :disabled-date="endDisabledDate"
          v-bind="$attrs.endOptions"
          :disabled="endDateDisable"
        >
        </el-date-picker>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.choose-date {
  display: flex;
}
</style>
